package serv;

import java.io.*;
import java.net.Socket;
import engine.*
;
public class Connexion extends Thread {
	private Socket client; 
	private BufferedReader in; 
	private PrintStream out;
	private int nbt;
	private Parser parser;
	private World w;
	private CheckWorld cw;
	private Boolean loop = true;
	private ThreadManager tm;
	private long time;
	
	public Connexion(Socket client_soc, int nbt, World w, ThreadManager tm) {
		this.client = client_soc;
		this.nbt = nbt;
		this.w = w;
		this.tm = tm;
		this.time = System.currentTimeMillis();
		
		// We add one player to world
		// A mutexer
		this.w.plusNbPlayersNow();
		
		try { 
			in = new BufferedReader (new InputStreamReader (client.getInputStream())); 
			out = new PrintStream(client.getOutputStream());
		} 
		catch (IOException e) { 
			try {
				client.close();
			} 
			catch (IOException e1){} 
			System.err.println(e.getMessage()); 
			return; 
		}
	}
	
	public void run() {
		
		try {
			
			// Methods for parsing the input streams 
			parser = new Parser();
			// Method that verify what the client has to draw
			cw = new CheckWorld(w.getNbPlayers(), w.getNbFanion());
			// Informations about one player
			w.getPlayers()[nbt] = new Player(w);
			
			//says to the client that it is connected
			//out.println("your are connected to the server");
			
			while (loop) {
				
				//Ticks  test
				long t = System.currentTimeMillis();
				if (t - this.time >= 333){
					// Print which thread is taking care of the client
					System.out.println("Thread "+nbt);
					
					// Message send by the client and send to the client
					String msg = "";
					String rsp = "";
					
					//ask the client if he is still conected
					out.println("?");
					System.out.println("? sent");
					
					//wait for a response that should be all the commands made during one tick
					msg = in.readLine();
					System.out.println("Client : "+msg);
					
					// Update of the X and Y and angle position of the player
					parser.readMsg(msg, w, nbt, tm);
					
					// Check the screen that has to be drawn by the client
					if (msg != "hello00"){
						System.out.println("Player "+nbt+" posY="+w.getPlayers()[nbt].getPosY());
						System.out.println("Player "+nbt+" posX="+w.getPlayers()[nbt].getPosX());
						System.out.println("Player "+nbt+" angle="+w.getPlayers()[nbt].getAngle());
						
						rsp = cw.check(w, nbt, tm);
						out.println(rsp);
					}
					
					out.flush();
					
					//Refresh the main time
					this.time = System.currentTimeMillis();
				}
				
			}
			w.getPlayers()[nbt].setPlayed(false);
			System.out.println("le Thread nb "+nbt+" est mort");
		} 
		catch (IOException e) {
			System.out.println("connexion : "+e.toString());
		} 
		
		finally {
			try {
				client.close();
			} 
			catch (IOException e) {}
		}
	}
	
	public void shinde(){
		this.loop = false;
	}
}
